package com.sikaryofficial.backend.service.points;

import com.sikaryofficial.backend.constant.RedisCacheKey;
import com.sikaryofficial.backend.service.IPointsDetailStrategy;
import com.sikaryofficial.common.core.constant.PointRuleConstant;
import com.sikaryofficial.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author : qinjinyuan
 * @desc : 文章被置顶服务
 * @date : 2023/10/31 19:03
 */
@Service(value = PointRuleConstant.ARTICLE_TOP_UP + IPointsDetailStrategy.SUFFIX)
@Slf4j
public class ArticleTopUpService extends AbstractPointService {
    @Resource
    private RedisService redisService;

    /**
     * 增加积分后校验
     *
     * @param userId
     * @return
     */
    @Override
    public boolean updatePoints(Long sourceId, Long userId) {
        // 带特定topic点赞
        String buildUnionKey = buildUnionKey(RedisCacheKey.ARTICLE_TOP_UP_POINTS_UNION, sourceId);
        // 检查 sourceId 与 userId 对只能得一次积分
        if (Boolean.TRUE.equals(redisService.hasKey(buildUnionKey))) {
            log.info("文章ID:{}置顶已获得过积分，跳过重复处理", sourceId);
            return false;
        }
        // 文章被置顶，当积分大于上限，则不继续增加积分
        boolean isOver = checkPointsOver(userId, PointRuleConstant.ARTICLE_TOP_UP, RedisCacheKey.ARTICLE_TOP_UP_POINTS_NUM);
        if (Boolean.TRUE.equals(isOver)) {
            log.error("文章被置 sourceId " + sourceId + " has already been awarded points.");
            return false;
        }
        // 没有超，则可以继续更新积分
        this.increasePoints(sourceId, userId, PointRuleConstant.ARTICLE_TOP_UP, "");
        // 增加后，进行统计缓存设置
        this.afterIncrease(userId, RedisCacheKey.ARTICLE_TOP_UP_POINTS_NUM);
        // 缓存用户对文章的积分获取时间
        redisService.setCacheObject(buildUnionKey, System.currentTimeMillis(), 15L, TimeUnit.DAYS);
        return true;
    }
}
